package com.company.cloud.common.ribbon.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import com.company.cloud.common.constant.CommonConstant;
import com.company.cloud.common.constant.ConfigConstants;
import com.company.cloud.common.context.LbIsolationContextHolder;

import cn.hutool.core.util.StrUtil;

import javax.servlet.Filter;

/**
 * 负载均衡隔离规则过滤器
 */
@ConditionalOnClass(Filter.class)
public class LbIsolationFilter extends OncePerRequestFilter {

	@Value("${" + ConfigConstants.CONFIG_RIBBON_ISOLATION_ENABLED + ":false}")
	private boolean enableIsolation;

	@Override
	protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
		System.out.println("+++++++++LbIsolationFilter : shouldNotFilter = "+enableIsolation);
		return !enableIsolation;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		try {
			String version = request.getHeader(CommonConstant.VERSION_HEADER);
			System.out.println("+++++++++++LbIsolationFilter : 执行负载均衡隔离规则过滤器 version="+version);
			if (StrUtil.isNotEmpty(version)) {
				LbIsolationContextHolder.setVersion(version);
			}
			filterChain.doFilter(request, response);
		} finally {
			LbIsolationContextHolder.clear();
		}

	}

}
